#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <pthread.h>
#include <cstring>
#include <cassert>
using namespace std;

static void Usage(const std::string name)
{
    cout << "Usage:\n\t" << name << " server_ip server_port" << endl;
}

struct sockaddr_in server;

void *recverAndPrint(void *args)
{
    while (true)
    {
        int sockfd = *(int *)args;
        char buffer[1024];
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t s = recvfrom(sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&temp, &len);
        if (s > 0)
        {
            buffer[s] = 0;
            cout << "server echo# " << buffer << endl;
        }
    }
}

// ./udpServer serer_ip server_port
// 客户端要连接服务端，必须知道server对应的ip和port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    // 1.根据命令行，设置要访问的服务器IP
    string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    // 2.创建客户端
    // 2.1 创建socket
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    assert(sockfd > 0);

    // 2.2 填写服务器对应的信息
    bzero(&server, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(server_port);
    server.sin_addr.s_addr = inet_addr(server_ip.c_str());

    pthread_t t;
    pthread_create(&t, nullptr, recverAndPrint, (void *)&sockfd);
    // 3.通信过程
    string buffer;
    while (true)
    {
        cout << "Please Enter# ";
        getline(cin, buffer);

        // 发送消息给server
        sendto(sockfd, buffer.c_str(), buffer.size(), 0, (const struct sockaddr *)&server, sizeof(server)); // 首次调用sendto函数的时候，client会自动bind自己的IP和port
    }

    close(sockfd);
    return 0;
}